package com.android.BluethootChess.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;

import com.android.BluethootChess.connectivity.ComunicationFactory;
import com.android.BluethootChess.connectivity.ConnectionManagerFactory;
import com.android.BluethootChess.model.PieceColor;
import com.android.BluethootChess.util.Utils;

public class AdvanceToGame extends Activity {
	
	/** Called when the activity is first created. **/
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.advance_to_game);

		Button createGame = (Button) findViewById(R.id.createGameButton);
		createGame.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				initServer();
				Intent myIntent = new Intent(view.getContext(),
						BluethootChess.class);
				startActivity(myIntent);
			}

		});

		Button joinGame = (Button) findViewById(R.id.joinGameButton);
		joinGame.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				initClient();
				Intent myIntent = new Intent(view.getContext(),
						BluethootChess.class);
				startActivity(myIntent);
				// quitProcess();
			}
		});

	}

	private void initServer() {
		ComunicationFactory factory=ConnectionManagerFactory.getFactory();
		Utils.COMUNICATION = factory.getServer();
		Utils.PLAYING_COLOR = PieceColor.WHITE; 
	}

	private void initClient() {
		ComunicationFactory factory=ConnectionManagerFactory.getFactory();
		Utils.COMUNICATION = factory.getClient();
		Utils.PLAYING_COLOR = PieceColor.BLACK;
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if ((keyCode == KeyEvent.KEYCODE_BACK)) {
			Intent myIntent = new Intent(AdvanceToGame.this,
					NewGameActivity.class);
			AdvanceToGame.this.startActivity(myIntent);
			quitProcess();
		}

		return super.onKeyDown(keyCode, event);
	}

	protected void quitProcess() {
		super.onDestroy();
		android.os.Process.killProcess(android.os.Process.myPid());
	}
}